# -*- coding: cp1254 -*-
import django.dispatch
from django.db import models
from django.contrib.auth.models import User
from random import randint,randrange

dem_names = ('Abetatas', 'Aledil', 'Esalutin', 'Etkan', 'Hitozeyh', 'Ivixen', 'Iyenoral', 'Kened', 'Liteb', 'Odiroveh', 'Ranozaba', 'Rela', 'Rerobub', 'Rikda', 'Risared', 'Riye', 'Rotra', 'Senakina', 'Vakidrir', 'Anean', 'Anzid', 'Axatoz', 'Bovareot', 'Turafmor', 'Undat', 'Xolidedi', 'Xuzan', 'Yraba')
def_names = ('Erissare', 'Termanin', 'Irinde', 'Estird', 'Ardarume', 'Elanin', 'Taarum', 'Viranirn', 'Nalcarum', 'Estirdar', 'Celria', 'Calmanin', 'Elaninde', 'Erissa' )
hum_names = ('Nia', 'Adrogde', 'Arejand', 'Altdon', 'Erarm', 'Thom', 'Eobne', 'Lar', 'Starlert', 'Ivatd', 'Edarew', 'Anarny', 'Edantopher', 'Taew', 'Aliatopher', 'Nicny', 'Sogvid', 'Edaew', 'Ju', 'Alle')
orm_names = ('Largasha Bashnag', 'Mashag Rush', 'Rulfim Yak', 'Yadba', 'Ulamul Ghashn', 'Gakkenfe Lumbakh', 'Shakh Bogadb', 'Uramulg Lumbuk', 'Yadbaam Shadbu', 'Bugdul Shadbu', 'Mashagam Yagadbu', 'Bagamu Ugruma', 'Bogamul Khazor', 'Guaron Shagrak', 'Uramul Kharz', 'Lugdul Murgol', 'Ugdul Glorku', 'Lugdul Shamub', 'Shakh Shadbuk', 'Atulg Olorku' )
hef_names = ('Culumani', 'Elaninde', 'Erissa', 'Calmanin', 'Anirne', 'Termanin', 'Erissare', 'Calman', 'Estirdar', 'Elanin', 'Viranirn', 'Fistirne', 'Imarume', 'Estird', 'Ardaru' )

class GenericObject(models.Model): 
    y=models.IntegerField()
    name = models.CharField(max_length=20,blank=True)
    type = models.CharField(max_length=5)

class Skill(models.Model):
    name = models.CharField(max_length=30)
    message = models.CharField(max_length=150)
    category = models.CharField(max_length=10)
    subcategory = models.CharField(max_length=10)
    value=models.IntegerField()

    def effect(self,target):
        if self.category=="active":
            exec("target."+self.subcategory+" += self.value")
        elif self.category=="passive":
            exec("self."+self.subcategory+" += self.value")

'''class Spell(Skill):
    
    def effect(self',target):
        if self.category=="restore":
            exec("target."+self.subcategory+" += self.value")
        elif self.category=="damage":
            exec("target."+self.subcategory+" -= self.value")'''

class Item(GenericObject):

        category=models.CharField(max_length=30)
        typeclass=models.CharField(max_length=30)
        
        owner = models.OneToOneField('Character',related_name='owner',null=True)
        marked = models.BooleanField()
        in_use = models.BooleanField()
        
        effect=models.TextField()
        value=models.IntegerField()
        
        x=models.IntegerField()
                
        def use(self,user):
            if self.typeclass == 'material':#category should be edible, drinkable, unique, solid.
                if self.category == 'edible':
                    user.HP += self.value/2
                    return "HP gained ("+self.value/2+"pts. )"
                    delete(self)
            elif self.typeclass == 'document':#category should be book,document,map,pinting,note.
                data = str(self.category)
                return data
            elif self.typeclass == 'tool':
                exec("if user."+self.category+" == None: user."+self.category+"=self")#Category should be shirt,boots,pants,gloves,hat
                user.inventory.remove(self)
                    
class Character(GenericObject):

    race = models.CharField(max_length=10)
    gender = models.CharField(max_length=10)
    state = models.IntegerField()
    user = models.ForeignKey(User,null=True)
    npc = models.ForeignKey('NPC',null=True)
    current_place = models.CharField(max_length=50,blank=True)
    x=models.IntegerField()
    
    shirt = models.ForeignKey(Item,null=True,related_name="shirt")
    pants = models.ForeignKey(Item,null=True,related_name="pants")
    boots = models.ForeignKey(Item,null=True,related_name="boots")
    gloves = models.ForeignKey(Item,null=True,related_name="gloves")
    hat = models.ForeignKey(Item,null=True,related_name="hat")
    
    s_str=models.IntegerField()#strength
    s_int=models.IntegerField()#intelligence
    s_dex=models.IntegerField()#dexterity
    s_wis=models.IntegerField()#wisdom
    s_sta=models.IntegerField()#stamina
    s_luk=models.IntegerField()#luck
    empty=models.IntegerField()#distrubutable stats
    
    HP=models.IntegerField()
    a_maxhp= models.IntegerField()#Maximum HP
    MP=models.IntegerField()
    a_maxmp=models.IntegerField()#Maximum MP
    
    inventory = models.ManyToManyField(Item)
    #spellbook = models.ManyToManyField(Spell)

    contacts = models.ManyToManyField("Character")
    
    @staticmethod
    def init(request,name='NPC',race='NPC',sex='NPC'):
        chr = Character.objects.create(name=name,type='char',race=race,gender=sex,current_place="Marnaw",x=randint(70,550),y=randint(330,385),user=request.user,state=0,empty=0,s_str=randint(3,5),s_int=randint(3,5),s_dex=randint(3,5),s_sta=randint(3,5),s_wis=randint(3,5),s_luk=randint(3,5),HP=1,MP=1,a_maxhp=1,a_maxmp=1)
        if chr.race is not 'NPC': chr.race=race
        else: chr.race = [ "Dark Elf", "High Elf" , "Human", "Orc"][randint(0,3)]
        if chr.gender is not 'NPC': chr.gender=sex
        else: chr.gender= ['m','f'][randint(0,1)]
        if chr.name is not 'NPC':
            chr.npc=NPC.objects.create(char1=Character.init(request),char2=Character.init(request),char3=Character.init(request))
        else: chr.user = None
            
        
        if chr.race=="Dark Elf":
            if chr.name is 'NPC' and chr.gender is 'f': chr.name = def_names[randint(0,14)]
            elif chr.name is 'NPC' and  chr.gender is 'm': chr.name = dem_names[randint(0,25)]
            chr.s_wis += 1
            chr.s_dex += 1
            chr.s_str += 1
        elif chr.race=="High Elf":
            if chr.name is 'NPC': chr.name = hef_names[randint(0,14)]
            chr.s_str -= 1
            chr.s_int += 3
            chr.s_wis += 2
        elif chr.race=="Human":
            if chr.name is 'NPC': chr.name = hum_names[randint(0,18)]
            chr.s_str += 2
            chr.s_sta += 2
        elif chr.race=="Orc":
            if chr.name is 'NPC': chr.name = orm_names[randint(0,14)]
            chr.s_str += 6
            chr.s_int -= 1
            chr.s_sta += 2
        
        chr.a_maxhp=(chr.s_str*3.75+chr.s_dex*1.25+chr.s_sta*2.00+chr.s_luk*1.00)
        chr.HP=chr.a_maxhp
        chr.a_maxmp=(chr.s_int*4.00+chr.s_sta*0.75+chr.s_wis*2.25+chr.s_luk*1.00)
        chr.MP=chr.a_maxmp
        
        
        p=Place.objects.get(name="Marnaw")
        p.people.add(chr)
        p.save()
        chr.save()
        
        return chr

        
    
    def travel(self,__place):
        p1=Place.objects.get(name=self.current_place)
        for otherone in self.contacts.all():
            if(self.current_place!=otherone.current_place):
                self.contacts.remove(otherone)
                otherone.contacts.remove(self)
        p2=Place.objects.get(name=__place)
        p1.people.remove(self)
        p2.people.add(self)
        self.current_place=__place
        p1.save()
        p2.save()
        self.x=randint(60,550)
        self.y=randint(330,385)
        self.save()
        if self.npc is not None:
            self.npc.operate_chars()
                

    def interreact(self,contact):
        self.contacts.append(contact)
    
    def attack_to(self,opponent):
                
        if state:
            opponent.receive_effect("HP",-((self.__str+self.__luk)*0.75))
            self.end_turn()
            opponent.end_turn()
    
    def receive_effect(self,base,effect):
        
        exec("self."+base+" += effect")
        
        
    def end_turn(self):
    
        if self.HP>self.__maxhp: self.HP=self.__maxhp
        elif self.HP<0: 
            self.HP=0
            self.state=0
            
        if self.MP>self.__maxmp: self.MP=self.__maxmp
        elif self.MP<0: self.MP=0

    def learn_spell(self,spell):
        #self.spellbook.append(spell)
        self.save()

    def take_item(self,item):
        p=Place.objects.get(name=self.current_place)
        p.people.remove(id=item.id)
        self.inventory.append(item)
        item.owner=self
        item.marked=True
        self.save()
        p.save()
        
    def return_all(self):
        return {"name":self.name,"race":self.race,"gender":self.gender,"str":self.s_str,"int":self.s_int,"dex":self.s_dex,"wis":self.s_wis,"sta":self.s_sta,"luk":self.s_luk,"empty":self.empty,"HP":self.HP,"MP":self.MP,"maxHP":self.a_maxhp,"maxMP":self.a_maxmp,"hat":self.hat,"shirt":self.shirt,"gloves":self.gloves,"pants":self.pants,"boots":self.boots}
 
    #def level_up():
    
        #purple spaces
        
class NPC(models.Model):
    char1 = models.ForeignKey(Character,related_name='chr1')
    char2 = models.ForeignKey(Character,related_name='chr2')
    char3 = models.ForeignKey(Character,related_name='chr3')
    
    def operate_chars(self):
        op1 = randrange(0,2)
        op2 = randrange(0,2)
        op3 = randrange(0,2)
        
        if op1:
            p=Place.objects.get(name=self.char1.current_place)
            where = p.connection.all();
            to = where[randint(0,len(where)-1)]
            self.char1.travel(to.name)
        if op2:
            p=Place.objects.get(name=self.char2.current_place)
            where = p.connection.all();
            to = where[randint(0,len(where)-1)]
            self.char2.travel(to.name)
        if op3:
            p=Place.objects.get(name=self.char3.current_place)
            where = p.connection.all();
            to = where[randint(0,len(where)-1)]
            self.char3.travel(to.name)

class Place(models.Model):
    
    name = models.CharField(max_length=30)
    category = models.CharField(max_length=10)
    connection = models.ManyToManyField("self",symmetrical=True)
    items = models.ManyToManyField(Item,related_name='stuff')
    people = models.ManyToManyField(GenericObject)

class InterreactionBox(GenericObject):
    first = models.ForeignKey(Character,related_name='talker')
    second = models.ForeignKey(Character,related_name='listener')
    message_box = models.TextField()
    item_box1 = models.ManyToManyField(Item,related_name='tfbox')
    item_box2 = models.ManyToManyField(Item,related_name='esbox')
    current_place = models.CharField(max_length=50,blank=True)
    x=models.IntegerField()

    def decompose(self):
        p=Place.objects.get(name=self.current_place)
        p.people.add(self.first)
        p.people.add(self.second)
        p.save()
        self.first.state=0
        self.second.state=0
        for item in self.item_box1.all():
            self.first.inventory.add(item)
        for item in self.item_box2.all():
            self.second.inventory.add(item)
        self.first.save()
        self.second.save()
        self.delete()
    
    def __unicode__(self):
        return self.message_box